/**
 * ChatWindow 好友相关逻辑模块
 * 包含好友详情、选择、备注等功能
 */

import { ref, computed, type Ref, type ComputedRef } from 'vue'
import { useQuasar } from 'quasar'
import { nextTick } from 'vue'
import type { useChatStore } from '../stores/chat'

export interface FriendModuleDeps {
  $q: ReturnType<typeof useQuasar>
  chatStore: ReturnType<typeof useChatStore>
  leftMenuActive: Ref<string>
  selectedFriend: Ref<any>
  recentChatUsers: Ref<any[]>
  selectUser: (userId: string) => Promise<void>
  loadUserList: () => Promise<void>
  handleVoiceCall: () => Promise<void>
  handleVideoCall: () => Promise<void>
  callModule: {
    videoCallTargetUserId: Ref<string | null>
    videoCallTargetName: Ref<string | null>
  }
}

/**
 * 创建好友相关功能
 */
export function useChatWindowFriend(deps: FriendModuleDeps) {
  const {
    $q,
    chatStore,
    leftMenuActive,
    selectedFriend,
    recentChatUsers,
    selectUser,
    loadUserList,
    handleVoiceCall,
    handleVideoCall,
    callModule,
  } = deps

  // 好友列表页面选中的好友
  const selectedFriendId = computed(() => {
    if (!selectedFriend.value) return null
    return selectedFriend.value.user?.open_id || selectedFriend.value.to_id || null
  })

  // 处理显示好友详情（从好友列表触发）
  const handleShowFriendDetails = async (friend: { to_id: string; remark?: string; user?: { name?: string } }) => {
    // 这个函数主要用于设置详情抽屉的状态，实际显示由详情抽屉模块处理
    // 这里只处理好友相关的逻辑
    selectedFriend.value = friend
  }

  // 处理从好友列表选择好友（切换到聊天窗口）
  const handleSelectFriendFromList = async (friendId: string) => {
    // 切换到最近聊天页面
    leftMenuActive.value = 'recent'
    // 等待菜单切换完成
    await nextTick()
    // 选择该好友并打开聊天窗口
    await selectUser(friendId)
  }

  // 处理从好友列表显示用户详情（在好友列表页面）
  const handleShowFriendDetailsFromList = async (friend: any) => {
    // 设置选中的好友，这样右侧会显示用户详情面板
    selectedFriend.value = friend
  }

  // 处理发送消息给好友（从用户详情面板）
  const handleSendMessageToFriend = (friendId: string) => {
    // 切换到最近聊天页面并选择该好友
    leftMenuActive.value = 'recent'
    selectUser(friendId)
  }

  // 处理更新好友备注
  const handleUpdateFriendRemark = async (friendId: string, remark: string) => {
    try {
      const { updateFriendRemark } = await import('../services/im-friendship')
      await updateFriendRemark(friendId, remark || undefined)
      $q.notify({
        type: 'positive',
        message: '备注已更新',
      })
      // 更新选中的好友信息
      if (selectedFriend.value && selectedFriend.value.to_id === friendId) {
        selectedFriend.value.remark = remark
      }
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '更新备注失败',
      })
    }
  }

  // 处理来自好友详情面板的语音通话
  const handleVoiceCallFromFriend = async (friendId: string, friendName: string) => {
    // 设置临时通话目标
    callModule.videoCallTargetUserId.value = friendId
    callModule.videoCallTargetName.value = friendName
    // 调用语音通话函数
    await handleVoiceCall()
  }

  // 处理来自好友详情面板的视频通话
  const handleVideoCallFromFriend = async (friendId: string, friendName: string) => {
    // 设置临时通话目标
    callModule.videoCallTargetUserId.value = friendId
    callModule.videoCallTargetName.value = friendName
    // 调用视频通话函数
    await handleVideoCall()
  }

  // 处理从群组添加好友
  const handleAddFriendFromGroup = async (groupId: string) => {
    try {
      const { getGroupMembers } = await import('../services/im-group')
      const { getFriends } = await import('../services/im-friendship')
      const { getUserAsync } = await import('../services/auth')
      
      // 获取当前用户信息
      const currentUser = await getUserAsync()
      if (!currentUser) {
        throw new Error('未登录，请先登录')
      }
      const currentUserId = currentUser.open_id || (currentUser.snowflake_id ? String(currentUser.snowflake_id) : undefined) || String(currentUser.id)
      
      // 获取群成员列表
      const members = await getGroupMembers(groupId)
      
      // 获取好友列表，用于过滤已添加的好友
      const friends = await getFriends()
      const friendIds = new Set(friends.map(f => f.to_id))
      
      // 过滤掉当前用户和已经是好友的成员
      const availableMembers = members.filter(m => {
        const memberId = m.member_id
        return memberId !== currentUserId && !friendIds.has(memberId)
      })
      
      if (availableMembers.length === 0) {
        $q.notify({
          type: 'info',
          message: '群组中没有可添加的好友',
          position: 'top',
        })
        return
      }
      
      // 获取成员详细信息（名称）
      const { getUser } = await import('../services/message')
      const memberDetails = await Promise.all(
        availableMembers.map(async (m) => {
          try {
            const userInfo = await getUser(m.member_id)
            return {
              ...m,
              displayName: userInfo?.name || m.alias || m.member_id,
            }
          } catch (e) {
            return {
              ...m,
              displayName: m.alias || m.member_id,
            }
          }
        })
      )
      
      // 显示成员选择对话框
      $q.dialog({
        title: '从群组添加好友',
        message: `选择要添加的好友（共 ${availableMembers.length} 人）`,
        options: {
          type: 'radio',
          model: '',
          items: memberDetails.map(m => ({
            label: m.displayName,
            value: m.member_id,
          })),
        },
        cancel: true,
        persistent: true,
      }).onOk(async (memberId: string) => {
        if (!memberId) return
        
        try {
          const { addFriend } = await import('../services/im-friendship')
          await addFriend({
            to_id: memberId,
            add_source: 'group',
          })
          
          $q.notify({
            type: 'positive',
            message: '好友请求已发送',
            position: 'top',
          })
          
          // 重新加载好友列表
          await loadUserList()
        } catch (error: any) {
          $q.notify({
            type: 'negative',
            message: error.message || '添加好友失败',
            position: 'top',
          })
        }
      })
    } catch (error: any) {
      console.error('从群组添加好友失败:', error)
      $q.notify({
        type: 'negative',
        message: error.message || '从群组添加好友失败',
        position: 'top',
      })
    }
  }

  return {
    selectedFriend,
    selectedFriendId,
    handleShowFriendDetails,
    handleSelectFriendFromList,
    handleShowFriendDetailsFromList,
    handleSendMessageToFriend,
    handleUpdateFriendRemark,
    handleVoiceCallFromFriend,
    handleVideoCallFromFriend,
    handleAddFriendFromGroup,
  }
}

